package com.example.shortlink.util;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取请求参数工具类
 */
public class HttpParamUtil {

    /**
     * 获得url中参数
     *
     * @param url 请求路径
     * @return 参数集
     */
    public static Map<String, Object> getParameter(String url) {
        try {
            url = URLDecoder.decode(url, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        if (url.indexOf('?') != -1) {
            final String contents = url.substring(url.indexOf('?') + 1);
            return extracted(contents);
        }
        return Collections.emptyMap();
    }

    /**
     * 获取request中参数
     *
     * @param request 请求流
     * @return 参数集
     */
    public static Map<String, Object> getRequestParameters(HttpServletRequest request) {
        // 网址中的参数
        String urlParameter = request.getQueryString();
        if (urlParameter != null && urlParameter.length() != 0) {
            try {
                urlParameter = URLDecoder.decode(urlParameter, StandardCharsets.UTF_8.name());
                return extracted(urlParameter);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return Collections.emptyMap();
    }

    /**
     * 提取请求参数
     *
     * @param parameters 路径请求参数
     * @return map 参数集
     */
    private static Map<String, Object> extracted(String parameters) {
        Map<String, Object> map = new HashMap<>(16);
        String[] arr = parameters.split("&");
        for (String s : arr) {
            String key = s.substring(0, s.indexOf("="));
            String value = s.substring(s.indexOf("=") + 1);
            map.put(key, value);
        }
        return map;
    }

}
